<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
          <el-form-item label="" prop="type">
            <el-select v-model="queryParams.type" placeholder="预警阶段" clearable style="width: 200px">
              <el-option v-for="dict in ideaType" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="status">
            <el-select v-model="queryParams.status" placeholder="启用状态" clearable style="width: 200px">
              <el-option v-for="dict in statusType" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:user:add']">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList">
          <el-table-column label="编号" align="center" key="id" prop="id" v-if="columns[0].visible" />
          <el-table-column label="预警名称" align="center" key="name" prop="name" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="担保类型" align="center" key="loan_type_name" prop="loan_type_name" v-if="columns[2].visible" :show-overflow-tooltip="true" />
          <el-table-column label="担保产品" align="center" key="loan_id" prop="loan_id" v-if="columns[3].visible" width="120" />
          <el-table-column label="预警阶段" align="center" key="type_name" prop="type_name" v-if="columns[4].visible" width="120" />
          <el-table-column label="提前预警天数" align="center" key="days" prop="days" v-if="columns[5].visible" width="120" />
          <el-table-column label="预警周期" align="center" key="cycle" prop="cycle" v-if="columns[6].visible" width="120" />
          <el-table-column label="提醒时间" align="center" key="time" prop="time" v-if="columns[7].visible" :show-overflow-tooltip="true" />
          <el-table-column label="发送方式" align="center" key="way_type" prop="way_type" v-if="columns[8].visible" width="120" />
          <el-table-column label="启用状态" align="center" key="status" prop="status" v-if="columns[9].visible" width="120">
            <template #default="scope">
              <el-switch v-model="scope.row.status" active-value="1" inactive-value="0" @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="150" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="查看" placement="top">
                <el-button link type="primary" icon="View" @click="handleUpdate(scope.row, '查看')" v-hasPermi="['system:user:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:remove']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page_size" v-model:limit="queryParams.page_count" @pagination="getList" />
      </el-col>
    </el-row>
    <!-- 新增对话框 -->
    <el-dialog :title="titleName" v-model="addShow" width="630px" append-to-body>
      <el-form :hide-required-asterisk="disabledFlag" :disabled="disabledFlag" :model="form" :rules="rules" ref="warningRef" label-width="110px">
        <el-row>
          <el-col :span="17">
            <el-form-item label="预警名称" prop="name">
              <el-input v-model="form.name" placeholder="请为该预警定义一个名称" maxlength="30" />
            </el-form-item>
            <el-form-item label="担保类型" prop="loan_type">
              <el-select v-model="form.loan_type" placeholder="请选担保类型" style="width: 320px">
                <el-option v-for="dict in typeArr" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="担保产品" prop="loan_id">
              <el-select v-model="form.loan_id" placeholder="请选担保产品" style="width: 320px">
                <el-option v-for="dict in productArr" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="担保五级分类" prop="classify">
              <el-select v-model="form.classify" placeholder="请选择担保五级分类" style="width: 320px">
                <el-option v-for="item in classifyList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="预警阶段" prop="type">
              <el-select v-model="form.type" placeholder="请选择预警阶段" style="width: 320px">
                <el-option v-for="dict in ideaType" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="提前预警天数" prop="days">
              <el-input type="number" v-model="form.days" placeholder="" oninput="value=value.replace(/^0|[^0-9]/g, '')" />
            </el-form-item>
            <el-form-item label="预警周期" prop="cycle">
              <el-radio-group v-model="form.cycle" size="small">
                <el-radio :label="1">一次</el-radio>
                <el-radio :label="2">每天一次</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="预警发送时间" prop="time">
              <el-radio-group v-model="form.time" size="small">
                <el-radio label="10:00">10:00</el-radio>
                <el-radio label="14:00">14:00</el-radio>
                <el-radio label="18:00">18:00</el-radio>
                <el-radio label="22:00">22:00</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="发送方式" prop="way">
              <el-radio-group v-model="form.way" size="small">
                <el-radio :label="1">短信</el-radio>
                <el-radio :label="2">邮件</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-show="disabledFlag" label=" " prop="way_text">
              <el-input v-model="form.way_text" placeholder="" />
            </el-form-item>
            <el-form-item v-show="!disabledFlag" label="接收成员" prop="user">
              <el-select v-model="form.useArr" multiple placeholder="" style="width: 240px" @visible-change="visibleChange">
                <el-option v-for="item in memberList" :key="item.id" :label="item.real_name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否启用" prop="status">
              <el-switch v-model="form.status" class="ml-2" inline-prompt :active-value="1" :inactive-value="2" active-text="开启" inactive-text="关闭" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer" v-if="!disabledFlag">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Warning">
import { wayType, warningStageType, loanTypes } from "@/utils/dict";
import { loanWarnList, loanWarnQuery, loanWarnAdd, loanWarnUpdate, loanWarnUpdateState } from "@/api/afterLoan/index";
import { listProduct } from "@/api/product/product";
import { accountList } from "@/api/role";
import { getToken, getId } from "@/utils/auth";
import { format } from "echarts";
const { proxy } = getCurrentInstance();
const userList = ref([]);
const typeArr = ref([
  {
    value: 1,
    label: "个人信用",
  },
  {
    value: 2,
    label: "个人分期",
  },
  {
    value: 3,
    label: "个人分期",
  },
  {
    value: 4,
    label: "企业信用",
  },
  {
    value: 5,
    label: "企业分期",
  },
  {
    value: 6,
    label: "企业租赁",
  },
]);
const productArr = ref([]);
const titleName = ref("添加保后预警");
const disabledFlag = ref(false);
const addShow = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const classifyList = [
  { value: 1, label: "正常担保" },
  { value: 2, label: "关注担保" },
  { value: 3, label: "次级担保" },
  { value: 4, label: "可疑担保" },
  { value: 5, label: "损失担保" },
];
const ideaType = ref([
  { value: 2, label: "逾期预警" },
  { value: 1, label: "即将到期预警" },
]);
const statusType = ref([
  { value: "1", label: "开启" },
  { value: "2", label: "关闭" },
]);
const memberList = ref([]);
// 列显隐信息
const columns = ref([
  { key: 0, label: `编号`, visible: true },
  { key: 1, label: `预警名称`, visible: true },
  { key: 2, label: `担保类型`, visible: true },
  { key: 3, label: `担保产品`, visible: true },
  { key: 4, label: `预警阶段`, visible: true },
  { key: 5, label: `提前预警天数`, visible: true },
  { key: 6, label: `预警周期`, visible: true },
  { key: 7, label: `提醒时间`, visible: true },
  { key: 8, label: `发送方式`, visible: true },
  { key: 9, label: `启用状态`, visible: true },
]);

const data = reactive({
  form: {},
  queryParams: {
    page_size: 1,
    page_count: 10,
    type: undefined,
    status: "1",
  },
  rules: {
    name: [
      { required: true, message: "预警名称不能为空", trigger: "blur" },
      { min: 2, max: 20, message: "用户名称长度必须介于 2 和 20 之间", trigger: "blur" },
    ],
    type: [{ required: true, message: "请选择预警周期", trigger: "change" }],
    time: [{ required: true, message: "请选择预警发送时间", trigger: "change" }],
    status: [{ required: true, message: "请选择是否启用", trigger: "change" }],
    type: [{ required: true, message: "请选择预警阶段", trigger: "change" }],
    days: [{ required: true, message: "提前预警天数不能为空", trigger: "blur" }],
    useArr: [{ required: true, message: "接收成员不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);
/**获取担保产品列表*/
function getProductList() {
  listProduct({ page_size: 1, page_count: 100 }).then((res) => {
    res.data.list.forEach((element) => {
      if (element.status == "4" || element.status == "5") {
        productArr.value.push({ value: element.id, label: element.name });
      }
    });
    getList();
  });
}
function visibleChange(vl) {
  if (vl) {
    getUserList();
  }
}

/**获取用户*/
function getUserList() {
  accountList({ pageSize: queryParams.value.page_size, pageCount: queryParams.value.page_count }).then((res) => {
    if (res.list.length > 0) {
      memberList.value = res.list.map((item) => {
        item.id = item.id.toString();
        return item;
      });
    }
  });
}
/** 查询预警列表 */
function getList() {
  loading.value = true;
  loanWarnList(queryParams.value).then((res) => {
    console.log(res, "res");
    loading.value = false;
    total.value = res.data.total_page;
    if (res.data.total_page > 0) {
      userList.value = res.data.list.map((item) => {
        item["loan_type_name"] = loanTypes(item.loan_type);
        item["type_name"] = warningStageType(item.type);
        item.loan_id = productArr.value.filter((itm) => {
          return itm.value == item.loan_id;
        })[0].label;
        item.cycle = item.cycle == "1" ? "一次" : "每天一次";
        item["way_type"] = wayType(item.way);
        item.status = item.status.toString();
        return item;
      });
    } else {
      userList.value = [];
    }
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  console.log(queryParams.value, " queryParams.value");
  queryParams.value.page_size = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 用户状态修改  */
function handleStatusChange(row) {
  console.log(row, "row");
  let text = row.status === "1" ? "开启" : "关闭";
  proxy.$modal
    .confirm('确认要"' + text + '"吗?')
    .then(function () {
      return loanWarnUpdateState(row.id, row.status);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      console.log(row.status, "row.status");
      row.status = row.status === "0" ? "1" : "0";
    });
}
/** 取消按钮 */
function cancel() {
  addShow.value = false;
}
function resetForm() {
  form.value = {
    name: undefined,
    loan_type: undefined,
    loan_id: undefined,
    classify: undefined,
    type: undefined,
    days: 3,
    cycle: undefined,
    time: undefined,
    way: undefined,
    way_text: undefined,
    useArr: undefined,
    status: "1",
  };
  proxy.resetForm("warningRef");
}
/** 新增按钮操作 */
function handleAdd() {
  resetForm();
  addShow.value = true;
  disabledFlag.value = false;
  titleName.value = "添加保后预警";
}
/** 查看、修改按钮操作 */
function handleUpdate(row, type) {
  resetForm();
  getUserList();
  loanWarnQuery(row.id).then((res) => {
    form.value = res.data;
    form.value.useArr = res.data.user == "" ? res.data.user : res.data.user.split(",");
    if (type == "查看") {
      addShow.value = true;
      disabledFlag.value = true;
      titleName.value = "查看保后预警";
    } else {
      addShow.value = true;
      titleName.value = "修改保后预警";
      disabledFlag.value = false;
    }
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["warningRef"].validate((valid) => {
    if (valid) {
      let result = [];
      if (form.value.way == "1" || form.value.way == "2") {
        for (let i = 0; i < memberList.value.length; i++) {
          for (let j = 0; j < form.value.useArr.length; j++) {
            if (memberList.value[i].id == form.value.useArr[j]) {
              if (form.value.way == "1") {
                result.push(memberList.value[i].phone);
              } else if (form.value.way == "2") {
                result.push(memberList.value[i].email);
              }
            }
          }
        }
      }
      if (result.length == 0) {
        result = "";
      }
      if (titleName.value == "添加保后预警") {
        loanWarnAdd({
          ...form.value,
          user: form.value.useArr?.toString(),
          way_text: result?.toString(),
        }).then((response) => {
          addShow.value = false;
          proxy.$modal.msgSuccess("新增成功");
          getList();
        });
      } else {
        loanWarnUpdate({
          ...form.value,
          user: form.value.useArr?.toString(),
          way_text: result?.toString(),
        }).then((response) => {
          addShow.value = false;
          proxy.$modal.msgSuccess("修改成功");
          getList();
        });
      }
    }
  });
}
getProductList();
</script>
<style scoped>
.explain {
  line-height: 40px;
  font-size: 12px;
  margin-left: 90px;
}
</style>
